<?php

namespace cms\modules\v1\models\access;

use cms\modules\v1\models\admin\Admin;
use cms\modules\v1\models\admin\AdminRole;
use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "project_info".
 *
 * @property int    $id
 * @property string $name
 */
class ModuleActions extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%module_actions}}';
    }

    /**
     * 获取修改信息
     * @param int $moduleId
     * @return array
     */
    public function getInfo($moduleId = 0) {
        try {
            if (empty($moduleId)) {
                throw new Exception('未知信息模块');
            }

            $actionList = static::getByWhere(['module_id' => $moduleId]);
            $action = null;
            foreach ($actionList as $key => $value) {
                $action[] = [
                    'method' => $value['method'],
                    'controller' => $value['controller'],
                    'action' => $value['action'],
                    'desc' => $value['desc'],
                    'type' => $value['type'],
                    'id' => $value['id'],
                ];
            }
            return Functions::formatRestAPI(0, '', $action);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {

            $post = Yii::$app->request->post();
            $moduleId = isset($post['moduleId']) ? $post['moduleId'] : 0;
            $actions = isset($post['actions']) ? $post['actions'] : [];
            $data = [];

            if (!$moduleId) {
                throw new Exception('未知模块');
            }

            //获取当前模块下已存入的action方法
            $list = static::getByWhere(['module_id' => $moduleId]);
            $ids = array_column($list,'id');
            $actionIds = array_column($actions,'id');
            //判断是否删除、修改、添加
            if ($actions) {
                //取出移除掉的ID
                $diffIds = array_diff($ids,$actionIds);

                //取出新增的Id 新增的Id就是id为0的数据

                //修改原先ID的内容
                $intersectIds = array_intersect($ids,$actionIds);


                //先删除
                if (static::getCountByWhere(['id' => $diffIds]) > 0) {
                    $resDelete = static::deleteAll(['id' => $diffIds]);
                    if (!$resDelete) {
                        throw new Exception('操作失败');
                    }
                }

                $data['module_id'] = $moduleId;
                //后添加
                foreach ($actions as $key => $value) {
                    $data['method'] = $value['method'];
                    $data['controller'] = $value['controller'];
                    $data['action'] = $value['action'];
                    $data['desc'] = $value['desc'];
                    $data['type'] = (int) $value['type'];

                    if (in_array($value['id'],$intersectIds)) {
                        //修改
                        $data['update_time'] = date('Y-m-d H:i:s');
                        $resUpdate = static::updateDataWithLog($data,['id' => $value['id']]);
                        if ($resUpdate === false) {
                            throw new Exception('操作失败');
                        }
                    }

                    if (empty($value['id']) || !$value['id']) {
                        //新增
                        $data['create_time'] = date('Y-m-d H:i:s');
                        $resInsert = static::insertDataWithLog($data);
                        if ($resInsert === false) {
                            throw new Exception('操作失败');
                        }
                    }
                }
            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function checkActions() {
        try {
            $user = (new Admin())->checkLogin();

            $roleInfo = AdminRole::getOneInfoById($user['role_type']);
            if($roleInfo['action_permissions'] == -1) {
                return true;
            }
            $actionPer = explode(",", $roleInfo['action_permissions']);

            $where['controller'] = strtolower(\Yii::$app->controller->id);
            $where['action'] = strtolower(\Yii::$app->controller->action->id);
            $where['method'] = strtolower(\Yii::$app->request->method);


            if (strtolower(\Yii::$app->request->method) == "options") {
                return true;
            }

            $actionInfo = ModuleActions::getOneByWhere($where);

            if (empty($actionInfo)) {
                return true;
            }

            if ($actionInfo['type'] == Status::COMMON_RADIO_NO) {
                return true;
            }

            if (!in_array($actionInfo['id'], $actionPer)) {
                throw new Exception('对不起，您没有该操作权限！');
            }

            return true;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function getChildrenByModuleId($moduleId = 0)
    {
        try {
            if (empty($moduleId)) {
                throw new Exception('数据不能为空');
            }

            #获取第一级
            $moduleList = static::getListMapByCache();
            $result = [];
            foreach ($moduleList as $v) {
                if ($v['module_id'] == $moduleId) {
                    $result[] = $v;
                }
            }
            return $result;
        } catch (Exception $e) {
            return [];
        }
    }


    public static function getDescByActionPermission($permission = '') {
        if (empty($permission)) {
            return [];
        }
        if (is_string($permission)) {
            $permission = explode(",", $permission);
        }

        $actionsMap = static::getListMapByCache();

        $result = [];
        foreach ($permission as $v) {
            if (array_key_exists($v, $actionsMap)) {
                $result[] = $actionsMap[$v]['desc'];
            }
        }

        return $result;
    }

}
